package main

import (
	"fmt"
	"gitee.com/wenxichang/sfont"
	"os"
	"path/filepath"
	"strings"
)

func main() {
	if len(os.Args) < 2 {
		fmt.Printf("用法: %s <soundfont文件>\n", filepath.Base(os.Args[0]))
		fmt.Println("示例: sfontinfo piano.sf2")
		os.Exit(1)
	}

	filename := os.Args[1]

	sf := &sfont.SoundFont{}
	err := sf.Read(filename)
	if err != nil {
		fmt.Printf("读取 SoundFont 文件失败: %v\n", err)
		os.Exit(1)
	}

	printEnhancedSoundFontInfo(sf)
}

func printEnhancedSoundFontInfo(sf *sfont.SoundFont) {
	fmt.Printf("\nSoundFont 文件分析: %s\n", sf.Path)
	fmt.Println("=" + strings.Repeat("=", 60))

	// 显示基本信息
	fmt.Printf("\n基本信息:\n")
	fmt.Printf("  名称: %s\n", sf.Name)
	fmt.Printf("  版本: %d.%d\n", sf.Version.Major, sf.Version.Minor)
	fmt.Printf("  引擎: %s\n", sf.Engine)
	fmt.Printf("  创建者: %s\n", sf.Creator)
	fmt.Printf("  产品: %s\n", sf.Product)
	fmt.Printf("  日期: %s\n", sf.Date)
	fmt.Printf("  注释: %s\n", sf.Comment)
	fmt.Printf("  版权: %s\n", sf.Copyright)
	fmt.Printf("  工具: %s\n", sf.Tools)

	// 显示预设信息
	if len(sf.Presets) > 0 {
		fmt.Printf("\n预设列表 (%d 个):\n", len(sf.Presets))
		fmt.Printf("  %-4s %-4s %-30s %-10s %-10s\n", "Bank", "Preset", "Name", "Bag Index", "Zones")
		fmt.Printf("  %-4s %-4s %-30s %-10s %-10s\n", "----", "------", "----", "---------", "-----")
		for _, preset := range sf.Presets {
			zoneCount := len(preset.Zones)
			fmt.Printf("  %-4d %-4d %-30s %-10d %-10d\n",
				preset.Bank, preset.Preset, preset.Name, preset.PresetBagIndex, zoneCount)
		}
	} else {
		fmt.Printf("\n预设列表: 无预设\n")
	}

	// 显示乐器信息
	if len(sf.Instruments) > 0 {
		fmt.Printf("\n乐器列表 (%d 个):\n", len(sf.Instruments))
		fmt.Printf("  %-30s %-10s %-10s\n", "Name", "Bag Index", "Zones")
		fmt.Printf("  %-30s %-10s %-10s\n", "----", "---------", "-----")
		for i, inst := range sf.Instruments {
			zoneCount := len(inst.Zones)
			fmt.Printf("  [%3d] %-30s %-10d %-10d\n",
				i+1, inst.Name, inst.InstrumentBagIndex, zoneCount)
		}
	} else {
		fmt.Printf("\n乐器列表: 无乐器\n")
	}

	// 显示样本信息
	if len(sf.Samples) > 0 {
		fmt.Printf("\n样本列表 (%d 个):\n", len(sf.Samples))
		fmt.Printf("  %-30s %-10s %-10s %-10s %-10s %-8s\n",
			"Name", "Start", "End", "Loop Start", "Loop End", "Rate")
		fmt.Printf("  %-30s %-10s %-10s %-10s %-10s %-8s\n",
			"----", "-----", "---", "---------", "-------", "----")
		for i := 0; i < len(sf.Samples); i++ {
			sample := sf.Samples[i]
			fmt.Printf("  %-30s %-10d %-10d %-10d %-10d %-8d\n",
				sample.Name, sample.Start, sample.End,
				sample.LoopStart, sample.LoopEnd, sample.SampleRate)
		}
	} else {
		fmt.Printf("\n样本列表: 无样本\n")
	}

	// 显示层级关系
	fmt.Printf("\n层级关系示例:\n")
	for i := 0; i < len(sf.Presets); i++ {
		preset := sf.Presets[i]
		fmt.Printf("\n  [%d] %s (Bank %d, Preset %d)\n",
			i+1, preset.Name, preset.Bank, preset.Preset)
		fmt.Printf("      区域数量: %d\n", len(preset.Zones))

		// 显示每个区域的信息
		for j, zone := range preset.Zones {
			fmt.Printf("      区域 [%d]:\n", j+1)
			fmt.Printf("        生成器数量: %d\n", len(zone.Generators))

			// 显示重要的生成器
			for _, gen := range zone.Generators {
				switch gen.Type {
				case sfont.Gen_Instrument:
					instIndex := int(gen.Amount.Word)
					if instIndex < len(sf.Instruments) {
						inst := sf.Instruments[instIndex]
						fmt.Printf("        引用乐器: %s (索引 %d)\n", inst.Name, instIndex)
					}
				case sfont.Gen_KeyRange:
					fmt.Printf("        键位范围: %d - %d\n", gen.Amount.LowByte, gen.Amount.HighByte)
				case sfont.Gen_VelRange:
					fmt.Printf("        力度范围: %d - %d\n", gen.Amount.LowByte, gen.Amount.HighByte)
				}
			}

			// 查找并显示引用的乐器和样本
			instruments := sf.FindPresetInstruments(i)
			if len(instruments) > 0 {
				fmt.Printf("        关联的乐器:\n")
				for _, inst := range instruments {
					fmt.Printf("          - %s\n", inst.Name)

					// 查找乐器引用的样本
					samples := sf.FindInstrumentSamples(findInstrumentIndex(sf, inst))
					if len(samples) > 0 {
						fmt.Printf("            样本:\n")
						for k, sample := range samples {
							if k < 3 { // 只显示前3个样本
								fmt.Printf("            - %s\n", sample.Name)
							} else if k == 3 {
								fmt.Printf("            - ... 还有 %d 个样本\n", len(samples)-3)
							}
						}
					}
				}
			}
		}
	}

	// 显示统计信息
	fmt.Printf("\n统计信息:\n")
	fmt.Printf("  预设数量: %d\n", len(sf.Presets))
	fmt.Printf("  乐器数量: %d\n", len(sf.Instruments))
	fmt.Printf("  样本数量: %d\n", len(sf.Samples))
	if sf.SampleData != nil {
		fmt.Printf("  样本数据大小: %.2f MB\n", float64(len(sf.SampleData))/(1024*1024))
	} else {
		fmt.Printf("  样本数据大小: 无数据\n")
	}

	// 显示区域统计
	totalPresetZones := 0
	for _, preset := range sf.Presets {
		totalPresetZones += len(preset.Zones)
	}

	totalInstrumentZones := 0
	for _, inst := range sf.Instruments {
		totalInstrumentZones += len(inst.Zones)
	}

	fmt.Printf("  预设区域总数: %d\n", totalPresetZones)
	fmt.Printf("  乐器区域总数: %d\n", totalInstrumentZones)
}

// 辅助函数：查找乐器索引
func findInstrumentIndex(sf *sfont.SoundFont, instrument *sfont.Instrument) int {
	for i, inst := range sf.Instruments {
		if inst == instrument {
			return i
		}
	}
	return -1
}
